package com.cwrl.spider.common.mq.config;

import cn.hutool.core.util.IdUtil;
import com.cwrl.spider.common.mq.core.SpiderMqTemplate;
import com.cwrl.spider.common.mq.domain.SpiderMqMessage;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * 基于 rabbit 实现的mq 默认使用的
 */
@Configuration(
        proxyBeanMethods = false
)
@ConditionalOnProperty(
        name = {"spring.spider.mq.type"},
        havingValue = "rabbit",
        matchIfMissing = true
)
public class RabbitMqConfiguration {
    @Bean
    public SpiderMqTemplate spiderMqAmqpTemplate(AmqpTemplate amqpTemplate) {
        return new SpiderMqTemplate() {
            @Override
            public <T> void send(String topic, T message) {
                SpiderMqMessage<?> mqMessage = SpiderMqMessage.builder()
                        .messageId(IdUtil.getSnowflakeNextIdStr())
                        .time(System.currentTimeMillis())
                        .message(message)
                        .build();
                amqpTemplate.convertAndSend(topic, mqMessage);
            }

            @Override
            public <T> void sendByBroadcast(String topic, T message) {

            }
        };
    }
}
